package _17_函数式编程.Lambda._9_Lambda应用;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class _9_4_Lambda_Predicate_Consumer {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("1","","3",null,"5");
        List<String> result;

        Predicate<String> predicate = (String str) -> !str.isEmpty();

        result = filter(list, predicate);

        Consumer<String> consumer = (String str) -> System.out.println(str);

        printByConsumer(result, consumer);
    }

    /**
     * 筛选
     * @param list
     * @param predicate
     * @param <T>
     * @return
     */
    public static <T> List<T> filter(List<T> list, Predicate<T> predicate){
        List<T> result = new ArrayList<>();
        for (T t : list){
            if(t != null && predicate.test(t)){
                result.add(t);
            }
        }
        return result;
    }

    /**
     * 输出
     * @param list
     * @param consumer
     * @param <T>
     */
    public static <T> void printByConsumer(List<T> list, Consumer<T> consumer){

        for (T t : list){
            consumer.accept(t);
        }
    }

}
